package com.ksd.web.controller.upload;

import com.ksd.common.utils.file.FileUploadUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipCompressor {

    public static void zipFileOrDirectory(String sourcePath, String zipFilePath) throws IOException {
        FileOutputStream fos = new FileOutputStream(zipFilePath);
        ZipOutputStream zipOut = new ZipOutputStream(fos);
        File fileToZip = new File(sourcePath);

        zipFile(fileToZip, fileToZip.getName(), zipOut);

        zipOut.close();
        fos.close();
    }

    private static void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException {
        if (fileToZip.isHidden()) {
            return;
        }
        if (fileToZip.isDirectory()) {
            if (fileName.endsWith("/")) {
                zipOut.putNextEntry(new ZipEntry(fileName));
                zipOut.closeEntry();
            } else {
                zipOut.putNextEntry(new ZipEntry(fileName + "/"));
                zipOut.closeEntry();
            }
            File[] children = fileToZip.listFiles();
            if (children != null) {
                for (File childFile : children) {
                    zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
                }
            }
            return;
        }
        FileInputStream fis = new FileInputStream(fileToZip);
        ZipEntry zipEntry = new ZipEntry(fileName);
        zipOut.putNextEntry(zipEntry);
        byte[] bytes = new byte[1024];
        int length;
        while ((length = fis.read(bytes)) >= 0) {
            zipOut.write(bytes, 0, length);
        }
        fis.close();
    }
    public static final String[] IMAGE_EXTENSION = { "bmp", "gif", "jpg", "jpeg", "png" ,"webp"};

    public static final String[] FILE_EXTENSION = { "swf", "flv","mp4","3gp","mts","ts","mov","mkv","avi" };
    public static void main(String[] args) {
//        String sourcePath = "path/to/your/source"; // 要压缩的文件或文件夹路径
//        String zipFilePath = "path/to/your/output.zip"; // 压缩后的 ZIP 文件路径
//        try {
//            zipFileOrDirectory(sourcePath, zipFilePath);
//            System.out.println("压缩完成！");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }


        String name = "C:\\Users\\wuyun\\Desktop\\电影测试包\\test.mp4";
        int i = name.lastIndexOf(".");
        System.out.println(i);
        String substring = name.substring(i+1, name.length());
        System.out.println(substring);
        if(FileUploadUtils.isAllowedExtension(substring,FILE_EXTENSION)){
            System.out.println("true");
        }else{
            System.out.println("false");
        }
    }
}
